package org.example.blogserver.user.controller;

import cn.hutool.Hutool;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.ibatis.annotations.Delete;
import org.example.blogcommon.base.utils.R;
import org.example.blogpojo.user.domain.User;
import org.example.blogpojo.user.query.UserQuery;
import org.example.blogserver.system.annotation.PreAuthorize;
import org.example.blogserver.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    @Operation (summary = "查所有", description = "查所有用户")
    public R findAll() {
        List<User> allUser = userService.getAllUser();
        return R.ok(allUser);
    }

    @GetMapping("/{id}")
    @Operation(summary = "id查", description = "id查")
    public R findAll(@PathVariable Long id) {
        User userById = userService.getUserById(id);
        return R.ok(userById);
    }

    @PostMapping
    @Operation(summary = "分页条件查询", description = "分页条件查询")
    public R queryPage(@RequestBody UserQuery userQuery) {
        PageInfo<User> userPageInfo = userService.queryPage(userQuery);
        return R.ok(userPageInfo);
    }

    @PutMapping
    @Operation(summary = "新增修改", description = "新增修改")
    public R insertandupdate(@RequestBody User user) {
        try {
            Long id = user.getId();
            if (id == null) {
                userService.insertUser(user);
            }else{
                userService.updateUser(user);
            }
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.fail();
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "通过id删除", description = "通过id删除")
    @PreAuthorize(name = "删除用户",sn="user:delete",descs = "删除用户")
    public R deleteById(@PathVariable Long id) {
        userService.deleteUser(id);
        return R.ok();
    }

    @PatchMapping
    @PreAuthorize (name = "批量删除用户",sn="user:deletes",descs = "批量删除用户")
    @Operation(summary = "批量删除", description = "通过id批量删除")
    public R deleteByIds(@RequestBody Long[] ids) {
        userService.deleteUserByIds(ids);
        return R.ok();
    }
}
